package com.yunkaweilai.android.activity.operation.MemberLock;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.yunkaweilai.android.R;
import com.yunkaweilai.android.activity.member.ConsumeRecordActivity;
import com.yunkaweilai.android.activity.member.MemberInfoActivity;
import com.yunkaweilai.android.activity.member.RechargeRecordActivity;
import com.yunkaweilai.android.activity.member.UpdateMemberInfoActivity;
import com.yunkaweilai.android.base.BaseActivity;
import com.yunkaweilai.android.base.BaseApplication;
import com.yunkaweilai.android.constants.Api;
import com.yunkaweilai.android.constants.CommonConstants;
import com.yunkaweilai.android.interfaces.MyDialogInterface;
import com.yunkaweilai.android.model.AppRuleModel;
import com.yunkaweilai.android.model.Event;
import com.yunkaweilai.android.model.LockQRBean;
import com.yunkaweilai.android.model.member.MemberHeadModel;
import com.yunkaweilai.android.model.member.MemberInfoModel;
import com.yunkaweilai.android.net.HttpRequest;
import com.yunkaweilai.android.net.PostProcess;
import com.yunkaweilai.android.utils.TitleBuilder;
import com.yunkaweilai.android.utils.Utils;
import com.yunkaweilai.android.view.dialog.LockPicDownloadDialog;
import com.yunkaweilai.android.view.dialog.member.MemberDelDialogForLock;
import com.yunkaweilai.android.view.dialog.member.MemberStatusDialogForLock;
import com.yunkaweilai.android.view.dialog.operation.DialogPayMoney;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 会员解锁
 */

public class LockActivity extends BaseActivity implements MyDialogInterface {
    @BindView(R.id.id_img_head)
    ImageView idImgHead;
    @BindView(R.id.id_tv_card_infor)
    TextView idTvCardInfor;
    @BindView(R.id.id_tv_name)
    TextView idTvName;
    @BindView(R.id.id_img_status)
    ImageView idImgStatus;//状态显示图片
    @BindView(R.id.id_tv_lock1)
    TextView idTvLock1;//文字1
    @BindView(R.id.id_tv_lock2)
    TextView idTvLock2;//文字2
    @BindView(R.id.id_tv_lock3)
    TextView idTvLock3;//文字3
    @BindView(R.id.id_tv_pay_last)
    TextView idTvPay;//列表显示解锁次数
    @BindView(R.id.id_tv_introduce)
    TextView idTvIntroduce;//介绍文字
    @BindView(R.id.id_tv_consume_record)
    TextView idTvConsume;//消费记录
    @BindView(R.id.id_tv_recharge_record)
    TextView idTvRecharge;//充值记录
    @BindView(R.id.id_tv_lock_btn)
    TextView idTvLockbtn;//锁定按钮
    @BindView(R.id.id_tv_change)
    TextView idTvChange;//修改解锁金额按钮
    @BindView(R.id.id_tv_activation)
    TextView idTvActivation;//生成解锁二维码按钮
    @BindView(R.id.id_tv_see)
    TextView idTvSee;//查看按钮
    @BindView(R.id.id_tv_modify)
    TextView idTvModify;//修改按钮
    @BindView(R.id.id_tv_del)
    TextView idTvDel;//删除按钮
    private MemberHeadModel model;
    public static final String MEMBER_MODEL = "MEMBER_MODEL";
    public static final String MEMBER_BUNDLE = "MEMBER_BUNDLE";
    private AppRuleModel.DataBean.InfoBean appRuleModel;

    public static void actionStart(Context context, MemberHeadModel model) {
        Intent intent = new Intent(context, LockActivity.class);
        Bundle bundle = new Bundle();
        bundle.putSerializable(MEMBER_MODEL, model);
        intent.putExtra(MEMBER_BUNDLE, bundle);
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_lock);
        ButterKnife.bind(this);
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
        appRuleModel = BaseApplication.getAppRuleModel();
        Intent intent = getIntent();
        model = (MemberHeadModel) intent.getBundleExtra(MEMBER_BUNDLE).getSerializable(MEMBER_MODEL);
        updateHead(model);
        initview();
        setImage();
        inithttp();
        new TitleBuilder(mAc).setLeftImage(R.mipmap.ic_go_back).setLeftOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        }).setTitleText("会员解锁");

    }

    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void onShopEvent(Event.OtherTypeEvent event) {
        if (event != null) {
            if (event.type == CommonConstants.MEMBER_INFO_LIST) {
                if (event.flag) {
                    refresh();
                }
            }
        }
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
    }

    private void refresh() {
        HttpRequest.postUrl(Api.MEMBER_INFO_BASIC)
                .addParams("member_id", model.getId())
                .execute(new PostProcess.StringCallBack() {
                    @Override
                    public void onResponse(String json) {
                        boolean codeInfoRs = Utils.checkCode(mAc, json);
                        if (codeInfoRs) {
                            Gson gson = new Gson();
                            MemberInfoModel memberInfoModel = gson.fromJson(json, MemberInfoModel.class);
                            model = memberInfoModel.getData().getList();
                            updateHead(model);
                        }
                    }

                    @Override
                    public void onError(Exception e) {
                    }
                });

    }

    private void initview() {
        if (model.getMl_status().equals("2") && !model.getStatus_info().is_valid() && !model.getMl_status().equals("3")) {
            idTvLock1.setVisibility(View.VISIBLE);
            idTvLock1.setText("解锁（激活）费用：" + model.getLock_price());
            green(idTvChange);
            green(idTvActivation);
        } else {
            idTvLock1.setVisibility(View.GONE);
            idTvLock1.setText("解锁（激活）费用：" + model.getLock_price());
            grey(idTvChange);
            grey(idTvActivation);
        }
        if (!Utils.isEmpty(model.getS_payment())) {
            idTvPay.setVisibility(View.VISIBLE);
            idTvPay.setText(model.getPay_time() + "   " + "解锁支付" + model.getS_payment());
        } else {
            idTvPay.setVisibility(View.GONE);
        }
        idTvLock2.setText("卡有效期：" + model.getValidtime());
        idTvLock3.setText("办卡职员：" + model.getCreate_name());
        idTvConsume.setText("消费记录(" + model.getConsume_order_count() + ")");
        idTvRecharge.setText("充值记录(" + model.getRecharge_order_count() + ")");

        if (model.is_edit()) {
            green(idTvModify);
            green(idTvDel);
        } else {
            grey(idTvModify);
            grey(idTvDel);
        }
    }

    private void inithttp() {
        HttpRequest.postUrl(Api.LOCK_SETTING)
                .execute(new PostProcess.StringCallBack() {
                    @Override
                    public void onResponse(String json) {
                        boolean checkcode = Utils.checkCode(json);
                        if (checkcode) {
                            Gson gson = new Gson();
//                            LockSettingBean lockSettingBean = gson.fromJson(json, LockSettingBean.class);
//                            idTvIntroduce.setText(Html.fromHtml(lockSettingBean.getData().getInfo().getCard_remark_str()));
                        }
                    }

                    @Override
                    public void onError(Exception e) {
                        showToast(e.getMessage());
                    }
                });
    }

    //设置卡的状态图
    private void setImage() {
        if (model.getStatus_info().is_valid()) {//过期
            idImgStatus.setImageResource(R.mipmap.ic_lock_valid);
            idTvLockbtn.setText("未锁定");
            grey(idTvLockbtn);
            grey(idTvChange);
            grey(idTvActivation);
            grey(idTvModify);
            grey(idTvDel);
        } else if (model.getMl_status().equals("3")) {//挂失
            idImgStatus.setImageResource(R.mipmap.ic_lock_lose);
            idTvLockbtn.setText("未锁定");
            grey(idTvLockbtn);
            grey(idTvChange);
            grey(idTvActivation);
            grey(idTvModify);
            grey(idTvDel);
        } else if (model.getMl_status().equals("1")) {//正常
            idImgStatus.setImageResource(R.mipmap.ic_lock_normal);
            idTvLockbtn.setText("未锁定");
        } else if (model.getMl_status().equals("2")) {//锁定
            idImgStatus.setImageResource(R.mipmap.ic_lock_lock);
            idTvLockbtn.setText("已锁定");
        }

    }

    //绿底白字
    @SuppressLint("ResourceAsColor")
    private void green(TextView textView) {
        textView.setClickable(true);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
            textView.setBackground(getResources().getDrawable(R.drawable.selector_guadan_bg_new));
            textView.setTextColor(getResources().getColor(R.color.white));
        }
    }

    //灰底黑字
    @SuppressLint("ResourceAsColor")
    private void grey(TextView textView) {
        textView.setClickable(false);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
            textView.setBackground(getResources().getDrawable(R.drawable.selector_guadan_bg2));
            textView.setTextColor(getResources().getColor(R.color.wjx_content_txt_light_black));
        }
    }

    //获取相关信息和二维码
    private void initQR() {
        HttpRequest.postUrl(Api.GET_QR)
                .addParams("member_id", model.getId())
                .execute(new PostProcess.StringCallBack() {
                    @Override
                    public void onResponse(String json) {
                        idTvActivation.setClickable(true);
                        dismissProgressDialog();
                        boolean checkcode = Utils.checkCode(json);
                        if (checkcode) {
                            Gson gson = new Gson();
                            LockQRBean lockQRBean = gson.fromJson(json, LockQRBean.class);
                            if (Utils.isEmpty(lockQRBean.getData().getInfo().getMember_tel())) {
                                showToast("请填写手机号码");
                            } else if (lockQRBean.getData().getInfo().getLock_price().equals("0.00") || lockQRBean.getData().getInfo().getLock_price().equals("0") || lockQRBean.getData().getInfo().getLock_price().equals("0.0")) {
                                showToast("请填写解锁费用");
                            } else {
                                LockPicDownloadDialog lockPicDownloadDialog = new LockPicDownloadDialog(mAc, lockQRBean);
                                lockPicDownloadDialog.show();
                            }
                        }
                    }

                    @Override
                    public void onError(Exception e) {
                        dismissProgressDialog();
                        idTvActivation.setClickable(true);
                        showToast(e.getMessage());
                    }
                });
    }

    //获取个人的支付金额
    private void initChange() {
        HttpRequest.postUrl(Api.GET_QR)
                .addParams("member_id", model.getId())
                .addParams("show_base_img", "1")
                .execute(new PostProcess.StringCallBack() {
                    @Override
                    public void onResponse(String json) {
                        idTvChange.setClickable(true);
                        dismissProgressDialog();
                        boolean checkcode = Utils.checkCode(json);
                        if (checkcode) {
                            Gson gson = new Gson();
                            LockQRBean lockQRBean = gson.fromJson(json, LockQRBean.class);
                            if (Utils.isEmpty(lockQRBean.getData().getInfo().getMember_tel())) {
                                showToast("请填写手机号码");
                            } else {
                                new DialogPayMoney(mAc, R.style.dialog, new DialogPayMoney.OnCloseListener() {
                                    @Override
                                    public void onClick(Dialog dialog, boolean confirm, String content) {
                                        if (confirm) {
                                            Utils.ManageMoney(content);
                                            changePay(content);
                                            dialog.dismiss();
                                        }
                                    }
                                }, lockQRBean.getData().getInfo().getLock_price(), "修改").show();
                            }
                        }
                    }

                    @Override
                    public void onError(Exception e) {
                        dismissProgressDialog();
                        showToast(e.getMessage());
                    }
                });
    }

    @OnClick({R.id.id_tv_consume_record, R.id.id_tv_recharge_record, R.id.id_tv_lock_btn, R.id.id_tv_change, R.id.id_tv_activation, R.id.id_tv_see, R.id.id_tv_modify, R.id.id_tv_del})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.id_tv_consume_record://充值记录
                ConsumeRecordActivity.actionStart(mAc, model);
                break;
            case R.id.id_tv_recharge_record://消费记录
                RechargeRecordActivity.actionStart(mAc, model);
                break;
            case R.id.id_tv_lock_btn:
                if (appRuleModel.isIs_super() || appRuleModel.getApp_rule().get("18")) {
                    MemberStatusDialogForLock dialog = null;
                    if ("1".equals(model.getMl_status())) {
                        dialog = new MemberStatusDialogForLock(mAc, LockActivity.this, model, "lock", "确认锁定会员？", idTvLockbtn, "2", idImgStatus);
                    } else if ("2".equals(model.getMl_status())) {
                        dialog = new MemberStatusDialogForLock(mAc, LockActivity.this, model, "lock", "确认解除锁定会员？", idTvLockbtn, "1", idImgStatus);
                    }
                    if (dialog != null) {
                        dialog.show();
                    }
                }
                break;
            case R.id.id_tv_change:
                idTvChange.setClickable(false);
                showProgressDialog("请稍等，读取数据中");
                initChange();
                break;
            case R.id.id_tv_activation:
                idTvActivation.setClickable(false);
                showProgressDialog("请稍等，读取数据中");
                initQR();
                break;
            case R.id.id_tv_see:
                MemberInfoActivity.actionStart(mAc, model, "2");
                break;
            case R.id.id_tv_modify://修改
                if (appRuleModel.isIs_super() || appRuleModel.getApp_rule().get("18")) {
                    if (model != null && model.is_edit()) {
                        UpdateMemberInfoActivity.actionStart(mAc, model);
                    } else {
                        showToast(R.string.member_updata_tip);
                    }
                }
                break;
            case R.id.id_tv_del://删除
                if (appRuleModel.isIs_super() || appRuleModel.getApp_rule().get("18")) {
                    if (model.is_edit()) {
                        MemberDelDialogForLock delDialog = new MemberDelDialogForLock(mAc, model.getId());
                        delDialog.show();
                    } else {
                        showToast(R.string.member_updata_tip);
                    }
                }
                break;
        }

    }

    //修改个人解锁费用
    private void changePay(final String money) {
        HttpRequest.postUrl(Api.DO_LOCK_PRICE)
                .addParams("member_id", model.getId())
                .addParams("lock_price", money)
                .execute(new PostProcess.StringCallBack() {
                    @Override
                    public void onResponse(String json) {
                        boolean checkcode = Utils.checkCode(json);
                        if (checkcode) {
                            idTvLock1.setText("解锁（激活）费用：" + money);
                            model.setLock_price(money);
                            showToast("修改成功");
                            EventBus.getDefault().post(new Event.TypeEvent(CommonConstants.MEMBER_LIST, true));
                        }
                    }

                    @Override
                    public void onError(Exception e) {
                        showToast(e.getMessage());
                    }
                });
    }

    //根据model修改会员头部信息
    private void updateHead(MemberHeadModel headModel) {
        Utils.MemberHeadImg(mAc, model.getMember_avatar(), model.getMember_sex(), idImgHead);
        idImgHead.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Utils.ImageEnlage(mAc, "1", model.getMember_avatar(), model.getMember_sex());
            }
        });
        idTvName.setText(headModel.getMember_name() + "(" + headModel.getLevel_name() + ": " + headModel.getCard_no() + ")");
        idTvCardInfor.setText("折扣：" + headModel.getDiscount() / 10 + "折   积分：" + headModel.getMember_points() + "   余额：" + headModel.getMember_price());
    }

    @Override
    public void RightClick() {
        idTvLock1.setVisibility(View.GONE);
        grey(idTvChange);
        grey(idTvActivation);
    }

    @Override
    public void CancelClick() {
        showProgressDialog();
        HttpRequest.postUrl(Api.GET_QR)
                .addParams("member_id", model.getId())
                .addParams("show_base_img", "1")
                .execute(new PostProcess.StringCallBack() {
                    @Override
                    public void onResponse(String json) {
                        dismissProgressDialog();
                        boolean checkcode = Utils.checkCode(json);
                        if (checkcode) {
                            Gson gson = new Gson();
                            LockQRBean lockQRBean = gson.fromJson(json, LockQRBean.class);
                            idTvLock1.setVisibility(View.VISIBLE);
                            idTvLock1.setText("解锁（激活）费用：" + lockQRBean.getData().getInfo().getLock_price());
                            green(idTvChange);
                            green(idTvActivation);
                        }
                    }

                    @Override
                    public void onError(Exception e) {
                        dismissProgressDialog();
                        showToast(e.getMessage());
                    }
                });

    }
}
